<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

/**
 * Base class for helpers.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package Simplify_Kernel
 */
abstract class Helper
{

  /**
   * 
   * @var IApplicationController
   */
  protected $app;
  
  /**
   * 
   * @var Config
   */
  protected $config;
  
  /**
   * 
   * @var IRequest
   */
  protected $request;
  
  /**
   * 
   * @var IResponse
   */
  protected $response;
  
  /**
   * 
   * @var IRouter
   */
  protected $router;

  /**
   * Constructor.
   * 
   * @return void
   */
  public function __construct()
  {
    $this->app = Simplify::getInstance();
    $this->config = Simplify::getConfig();
    $this->request = Simplify::getRequest();
    $this->response = Simplify::getResponse();
    $this->router = Simplify::getRouter();
  }

  /**
   *
   */
  public function __get($name)
  {
    return self::factory($name);
  }

  /**
   *
   * @param string $helper
   * @return Helper
   */
  public static function factory($helper)
  {
    $config = Simplify::getConfig();
    
    $name = Inflector::underscore($helper.'_helper');
    
    $dirs = $config->get('{env}:core:helpers:include_path')->getAll();
    while (count($dirs)) {
      $dir = array_shift($dirs);
      if (file_exists($dir.'/'.$name.'.php')) {
        require_once($dir.'/'.$name.'.php');
        break;
      }
    }
    
    if (! file_exists($dir.'/'.$name.'.php')) {
      throw new NotFoundException("Could not factory helper <b>$helper</b>: file not found");
    }
    
    $class = Inflector::camelize($name);
    
    if (! class_exists($class)) {
      throw new NotFoundException("Could not factory helper <b>$helper</b>: class not found");
    }
    
    $Helper = new $class();
    return $Helper;
  }

  /**
   *
   * @param $output
   * @return unknown_type
   */
  protected function output($output)
  {
    return $output;
  }

}

?>